<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title>生产计划</title>
		<link rel="stylesheet" href="../../../res/layui/css/layui.css" media="all">
		<link rel="stylesheet" href="../../../res/css/common/font-awesome.min.css" media="all">
		<link rel="stylesheet" href="../../../res/layui-config/css/app.css" media="all">
    </script>
	</head>
	<body>
		<div class="kit-table">
		    <form class="layui-form" lay-filter="kit-search-form">
				<!-- 左上角的两个按钮 -->
		        <div class="kit-table-header">
		            <div class="kit-search-btns">
		                <a href="javascript:;" data-action="add" class="layui-btn layui-btn-sm"><i class="layui-icon">&#xe608;</i> 新增</a>
		                <a href="javascript:;" data-action="del-bulk" class="layui-btn layui-btn-sm layui-btn-danger"><i class="layui-icon">&#xe640;</i> 批量删除</a>
		            </div>
		            <div class="kit-search-inputs">
		            	<div class="kit-search-keyword">
		                    <input type="text" class="layui-input" id="serach-one" placeholder="名称.." onKeyUp="lockInput(this,'serach-two')"/>
		                    <button lay-submit lay-filter="search"><i class="layui-icon">&#xe615;</i></button>
		                </div>
		                <div class="kit-search-more" id="kit-search-more">更多筛选<i class="layui-icon">&#xe61a;</i></div>
		            </div>
		        </div>
				<!-- 搜索扩展工具条 -->
		        <div class="kit-search-mored layui-anim layui-anim-upbit">
		            <div class="kit-search-body">
		            	<div class="layui-form-item">
		                    <label class="layui-form-label">计划名称</label>
		                    <div class="layui-input-block">
		                        <input type="text" name="pmcName" id="serach-two" placeholder="搜索关键字.." autocomplete="off" class="layui-input" onKeyUp="lockInput(this,'serach-one')">
		                    </div>
		                </div>
		                <div class="layui-form-item">
		                    <label class="layui-form-label">计划制造商</label>
		                    <div class="layui-input-block">
		                        <input type="text" name="comName" placeholder="制造商.." autocomplete="off" class="layui-input" >
		                    </div>
		                </div>
		                <div class="layui-form-item">
			                <label class="layui-form-label">开始日期</label>
			                <div class="layui-input-block">
				                    <input type="text" name="strStartTime" id="startDate" placeholder="yyyy-MM-dd" autocomplete="off" class="layui-input">
			                </div>
		                </div>
		                <div class="layui-form-item">
			                <label class="layui-form-label">生产期限</label>
			                <div class="layui-input-block">
				                    <input type="text" name="strEndTime" id="endDate" placeholder="yyyy-MM-dd" autocomplete="off" class="layui-input">
			                </div>
		                </div>
		                <div class="layui-form-item">
			                <label class="layui-form-label">属性</label>
			                <div class="layui-input-block">
			                	<input type="radio" name="pmcState" value="" title="不选" checked/>
			                	<input type="radio" name="pmcState" value="-1" title="未生产"/>
			                    <input type="radio" name="pmcState" value="0" title="生产中"/>
			                    <input type="radio" name="pmcState" value="1" title="已完成"/>
			                </div>
			            </div>
			            <div class="layui-form-item">
		                    <div class="layui-inline">
		                        <label class="layui-form-label">数量</label>
		                        <div class="layui-input-block">
			                        <div class="layui-input-inline" style="width: 40%;">
			                            <input type="text" name="minAmount" autocomplete="off" class="layui-input" maxlength="9" onKeyUp="amount(this)">
			                        </div>
			                        <div class="layui-form-mid">-</div>
			                        <div class="layui-input-inline" style="width: 40%;">
			                            <input type="text" name="maxAmount" autocomplete="off" class="layui-input" maxlength="9" onKeyUp="amount(this)">
			                        </div>
		                        </div>
		                    </div>
		                </div>
		            </div>
		            <div class="kit-search-footer">
		                <button type="reset" class="layui-btn layui-btn-sm layui-btn-primary kit-btn reset-btn">重置</button>
		                <button lay-submit lay-filter="search" class="layui-btn layui-btn-sm kit-btn">确定</button>
		            </div>
		        </div>
		    </form>
			<script type="text/html" id="pmc-edit-tpl">
				<div style="height: 145px;margin:auto;position: absolute;top: 0px;bottom: 0px;left: 0px;right: 0px">
					<form class="layui-form" action="" lay-filter="form-edit">
						<input type="hidden" name="pmcId" value="{{d.rowdata.pmcId}}" />
						<div class="layui-form-item">
			        		<label class="layui-form-label">计划日期</label>
			        		<div class="layui-input-block">
				       			<div class="layui-input-inline" style="width: 100%;">                    
		                      		{{# if(d.rowdata.strStartTime !== ''){}}
		                      			<input type="text" name="strStartTime" required lay-verify="required" value="{{d.rowdata.strStartTime}} 到 {{d.rowdata.strEndTime}}" id="planDate" placeholder="yyyy-MM-dd" autocomplete="off" class="layui-input">
		                      		{{#}else{}}
		                      			<input type="text" name="strStartTime" required lay-verify="required" id="planDate" placeholder="yyyy-MM-dd" autocomplete="off" class="layui-input">
		                      		{{#};}}
				       			</div>
			        		</div>
		        		</div>
						<div class="layui-form-item">
		                	<label class="layui-form-label">计划名称</label>
		                	<div class="layui-input-block">
		                    	<input type="text" name="pmcName" required lay-verify="required" value="{{d.rowdata.pmcName}}" placeholder="请输入名称" autocomplete="off" class="layui-input">
		                	</div>
		            	</div>
						<div class="layui-form-item">
		                	<label class="layui-form-label">计划制造商</label>
		                	<div class="layui-input-block">
		                    	<input type="text" name="comName" required lay-verify="required" value="{{d.rowdata.comName}}" placeholder="请输入制造商" autocomplete="off" class="layui-input">
		                	</div>
		            	</div>
						<div class="layui-form-item" style="display:none;">
		                	<div class="layui-input-block">
		                    	<button class="layui-btn" lay-submit lay-filter="formEdit">立即提交</button>
		                    	<button type="reset" class="layui-btn layui-btn-primary">重置</button>
		                	</div>
		            	</div>
					</form>
				</div>
			</script>
			<!-- 操作按钮 -->
		    <div class="kit-table-body">
		        <table id="demo" lay-filter="demo"></table>
		        <script type="text/html" id="tools">
		            <button class="layui-btn layui-btn-xs" lay-event="config">配置药品</button>
					<button class="layui-btn layui-btn-xs" lay-event="audit">提交审核</button>
		            <button class="layui-btn layui-btn-xs" lay-event="edit">编辑</button>
		            <button class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</button>
		        </script>
		        <script type="text/html" id="viwes">
					<button class="layui-btn layui-btn-xs" lay-event="detail">生产明细</button>
					<button class="layui-btn layui-btn-xs" lay-event="auditDetail">审核明细</button>
		        </script>
		    </div>
		</div>
		<script src="../../../res/js/common/jquery-1.11.2.min.js"></script>
		<script>
			//文本框只能输入金额
		    function amount(th){
		        var regStrs = [
		            ['^0(\\d+)$', '$1'], //禁止录入整数部分两位以上，但首位为0
		            ['[^\\d\\.]+$', ''], //禁止录入任何非数字和点
		            ['\\.(\\d?)\\.+', '.$1'], //禁止录入两个以上的点
		            ['^(\\d+\\.\\d{2}).+', '$1'] //禁止录入小数点后两位以上
		        ];
		        for(i=0; i<regStrs.length; i++){
		            var reg = new RegExp(regStrs[i][0]);
		            th.value = th.value.replace(reg, regStrs[i][1]);
		        }
		    }
			//搜索框同步输入
			function lockInput(obj,id){
				$("#"+id).val($(obj).val());
			}
		</script>
		<script src="../../../res/layui/layui.all.js"></script>
		<script>
			//弹出层下标
			var editIndex;
			//显示表格数据
		    layui.use(['table','laydate'], function() {
		        var table = layui.table,
		            $ = layui.jquery,
		            layer = layui.layer,
		            form = layui.form,
		            laytpl = layui.laytpl
		            laydate = layui.laydate;
		        var admin = getSession();
				var comId = admin==null ? null : admin.comId;
				var tableIns = table.render({
		            elem: '#demo',
		            sort:true,
		            height: 'full-50', //容器高度
		            url: '../../../pmc/showList.action',
		            page: true,
		            id: 'demo',
		            cols: [
		                [{checkbox: true,fixed: true},
		               	{title: '序号',type: 'numbers'},
		                {field: 'pmcName',title: '计划名称',width: 140},
		                {field: 'comName',title: '计划制造商',width: 100},
		                {field: 'pmcAmount',title: '数量',sort: true,width: 80},
		                {field: 'strStartTime',title: '开始时间',sort: true,width: 120},
		                {field: 'strEndTime',title: '生产期限',sort: true,width: 120},
		                {field: 'pmcState',title: '状态',width: 75},
		                {field: 'audState',title: '审核状态',width: 140},
		                {field: 'viwes',fixed: 'right',title: '查看',width: 165,align: 'center',toolbar: '#viwes'},
		                {field: 'tools',fixed: 'right',title: '操作',width: 280,align: 'center',toolbar: '#tools'}]
		            ],
		            done: function(res, curr, count) {
		            	var tableElem = this.elem.next('.layui-table-view');
		                $("[data-field = 'pmcState']").children().each(function(){
						    if($(this).text() == '1'){
						    	$(this).text("已完成");
						    } else if ($(this).text() == '0') {
						    	$(this).text("生产中...");
						    } else if ($(this).text() == '-1'){
						    	$(this).text("未生产");
						    }
					  	});
		                $("[data-field = 'audState']").children().not(":first").each(function(index){
		                	var id = $(this).parents('tr').find('td[data-field="pmcId"]').text();
		                	var o = $(this);
	            			if (o.text() == '10001') {
	            				o.html('<font style="color: #0000F0">等待财务审核</font>');
	            				tableElem.find('tr[data-index="' + index + '"]').find('td[data-field="viwes"] button[lay-event="auditDetail"],td[data-field="tools"] button').addClass('layui-btn-disabled').attr('disabled',true);
	            			} else if (o.text() == '10101' || o.text() == '10011') {
	            				o.html('<font style="color: #0000F0">等待总经理审核</font>');
	            				tableElem.find('tr[data-index="' + index + '"]').find('td[data-field="tools"] button').addClass('layui-btn-disabled').attr('disabled',true);
	            			} else if (o.text() == '10010') {
	            				o.html('<font style="color: #F00000">财务不通过</font>');
	            			} else if (o.text() == '10110') {
	            				o.html('<font style="color: #F00000">总经理不通过</font>');
	            			} else if (o.text() == '10111') {
	            				o.html('<font style="color: #00F000">通过</font>');
	            				tableElem.find('tr[data-index="' + index + '"]').find('td[data-field="tools"] button').addClass('layui-btn-disabled').attr('disabled',true);
	            			} else if (o.text() == '-1') {
	            				o.text("未审核");
	            				tableElem.find('tr[data-index="' + index + '"]').find('td[data-field="viwes"] button[lay-event="auditDetail"]').addClass('layui-btn-disabled').attr('disabled',true);
	            			}
					  	});
		            }
		        });
		        
		        renderDate('#startDate');
		        renderDate('#endDate');
		        
		     	//点击排序重新渲染表格
		        table.on('sort(demo)', function(obj){
		        	tableIns.reload();
		        });
		        
		        //监听搜索表单提交
		        form.on('submit(search)', function(data) {  
		            //带条件查询
		            tableIns.reload({
		                where: data.field,
		                page: { curr: 1 }
		            });
		            $('.kit-search-mored').hide();
		            return false;
		        });
		        
		        
		        //监听工具条按钮点击
		        table.on('tool(demo)', function(obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
		            var data = obj.data; //获得当前行数据
		            var layEvent = obj.event; //获得 lay-event 对应的值
		            var tr = obj.tr; //获得当前行 tr 的DOM对象
		
		            if (layEvent === 'detail') { //生产明细
		            	layer1(data.pmcId,data.pmcName);
		            } else if (layEvent === 'config') { //配置药品
		            	layer2(data.pmcId,data.pmcName);
		            } else if (layEvent === 'auditDetail') { //审核详情
		            	layer3(data.pmcId,data.audState);
		            } else if (layEvent === 'audit') { //提交审核
		            	$.ajax({ 
		            		url:"../../../pmc/check.action",
		            		data:{"comId":comId,"pmcId":data.pmcId},
		                    type:'post',//method请求方式，get或者post
		                    async:false,//同步
		                    dataType:'json',//预期服务器返回的数据类型
		                    success:function(mes){//res为相应体,function为回调函数
		                    	layer.msg(mes.msg);
		                    	if (mes.status==1) tableIns.reload();
		                    }
		                 });
		            } else if (layEvent === 'edit') { //编辑
		                var d = {
			                	rowdata: data
			                };
			            editLayer1(d);
			        } else if (layEvent === 'del') { //删除
		                layer.confirm('真的删除行么', function(index) {
		                	layer.close(index);
		                    update("../../../pmc/addOrUpdate.action",{"pmcId":data.pmcId,"isva":"0"});
		                });
		            }
		        });
		        
		        //表单渲染
		        form.render(null, 'kit-search-form');
		        //更多筛选点击事件
		        $('#kit-search-more').on('click', function() {
		            $('.kit-search-mored').toggle();
		        });
		        
		        //增加和修改弹出层   提交按钮点击事件
		        form.on('submit(formEdit)', function(data) {
                	var close = update("../../../pmc/addOrUpdate.action",data.field);
                	if (close) editIndex && layer.close(editIndex); //关闭弹出层
                	return false;
		        });
		        
		        //增加、批量删除 按钮点击事件
		        $('.kit-search-btns').children('a').off('click').on('click', function() {
		            var $that = $(this),
		                action = $that.data('action');
		            switch (action) {
		            	//点击的是 增加按钮
		                case 'add':
		                	var d = {
		                		//替换增加页面文本框内出现的undefine
		                        rowdata: {
		                        	pmcId: '',pmcName: '',strStartTime: '',strEndTime: '',comName: ''
		                        }
		                    };
		                	editLayer1(d);
		                    break;
		                    
		                //点击的是 批量删除按钮
		                case 'del-bulk':
		                    var d = table.checkStatus('demo');
		                    if (d.data.length === 0) {
		                        layer.msg('请选择要删除的数据');
		                        return;
		                    }
		                    var data = d.data,
		                        ids = [];
		                    layui.each(data, function(index, item) {
		                        ids.push(item.pmcId);
		                    });
		                    layer.confirm('真的删除行么', function(index) {
		                    	layer.close(index);
		                    	update("../../../pmc/bulkUpdate.action",ids);
			                });
		                break;
		            }
		        });
		    });
			
		  	//物料明细弹窗
			function layer1(id,name){
				var layerIndex1 = layer.open({
					  type: 2,
					  title: '药品明细',
					  content: '../../plan/pmc/details/index2.html?id='+id+"&name="+name,
					  area: ['100%', '100%']
					});
				layer.full(layerIndex1);
			}
			
		  	//配置药品弹窗
			function layer2(id,name){
				var layerIndex2 = layer.open({
				  type: 2,
				  title: '药品配置',
				  content: '../../plan/pmc/details/index.html?id='+id+"&name="+name,
				  area: ['100%', '100%']
				});
				layer.full(layerIndex2);
			}
		  	
			//审核详情弹窗
			function layer3(id,state){
				var layerIndex3 = layer.open({
				  type: 2,
				  title: '审核详情',
				  content: '../../audit/detail/pmcDetail.html?id='+id,
				  area: ['800px', '430px'],
				  maxmin: true,
				});
			}
		  	
			//渲染 药品修改和增加弹出层
		    function editLayer1(d){
	    		layui.laytpl($('#pmc-edit-tpl').html()).render(d,function(html) {
	    			editIndex = layer.open({
                        type: 1,
                        title: '药品操作',
                        content: html,
                        maxmin: true,
                        area: ['600px', '300px'],
                        btn: ['提交', '重置', '取消'],
                        yes: function(index, layero) {
                            $('form[lay-filter="form-edit"]').find('button[lay-submit]').click();
                        },
                        btn2: function(index, layero) {
                            $('form[lay-filter="form-edit"]').find('button[type="reset"]').click();
                            return false;
                        },
                        success: function() {
                            layui.form.render(null, 'form-edit');
                        }
                    });
                  	//日期下拉框渲染
       		 		var layd = laydate.render({
       	        	  elem: '#planDate'
       	        	  ,type: 'datetime'
       	        	  ,calendar: true
               	      ,range: '到'
               	      ,format: 'yyyy-M-d H:m:s'
               	      ,min: minDate(d)
               	      ,max: maxDate(d)
	               	  ,ready: function(){
	               		layd.hint('日期可选范围在<br> 6个月内');
	               	  }
       	        	});
                });
	    		return 
		    }
		    
		    //增加、修改、删除、批量删除 都是用的这一个方法
		    function update(url,data){
		    	var close = false;
		    	$.ajax({
		    		url: url,
                    type:'post',//method请求方式，get或者post
                    async:false,//同步
                    dataType:'json',//预期服务器返回的数据类型
                    data: JSON.stringify(data),//表格数据序列化
                    contentType: "application/json; charset=utf-8",
                    success:function(mes){//res为相应体,function为回调函数
                        if(mes.status==1){ 
                        	close = true;//有弹出层时是关闭弹出层 false不关闭
	                        $("#res").click();//调用重置按钮将表单数据清空
	                        $(".layui-laypage-btn")[0].click();//当前表格刷新
                        }
                        layer.msg(mes.msg);
                    },
                   	error:function(){layer.alert('数据异常，请稍后重试！！！',{icon:5});}
                 });
		    	return close;
		    }
		    
		    function addMouth(date, num) {
				//date为格式化后的日期字符yyyy-MM-dd,num为增加的月份 
				var monthnum = parseInt(num);
				var year = parseInt(date.substring(0, 4));
				var month = parseInt(date.substring(5, 7));
				var day = parseInt(date.substring(8, 10));
				var time = new Date(date).toLocaleTimeString('chinese', { hour12: false });
				if (month + monthnum > 12) {
					var newyear = year + 1;
					var newmonth = month + monthnum - 12;
					var newday = day;
				} else {
					var newyear = year
					var newmonth = month + monthnum;
					var newday = day;
				}
				var newdate = newyear + "-" + newmonth + "-" + newday + " " + time;
				return newdate;
			}
		    
		 	// 设置最小可选的日期
		    function minDate(d){
		        var now = new Date();
		        if (d.rowdata.strStartTime != null && d.rowdata.strStartTime != "") {
		        	return d.rowdata.strStartTime;
		        } else {
		        	return now.getFullYear()+"-" + (now.getMonth()+1) + "-" + now.getDate();
		        }
		    }
		 	
		 	// 设置最大可选的日期
		    function maxDate(d){
		        var now = new Date();
		        if (d.rowdata.strStartTime != null && d.rowdata.strStartTime != "") {
		        	return addMouth(d.rowdata.strStartTime,6);
		        } else {
		        	return now.getFullYear()+"-" + (now.getMonth()+6) + "-" + now.getDate();
		        }
		    }
		 	
		  	//日期下拉框渲染
		 	function renderDate(dateId){
		 		laydate.render({
	        	  elem: dateId
	        	  ,type: 'datetime'
	        	  ,calendar: true
        	      ,range: '到'
        	      ,format: 'yyyy-M-d H:m:s'
	        	});
		 	}
		    
		  	//重新渲染表单
		  	function renderForm(){ 
	  			layui.use('form', function(){ 
		  			var form = layui.form;//高版本建议把括号去掉，有的低版本，需要加() 
		  			form.render(); 
	  			}); 
	  		}
		  	
		  	function getSession(){
				var admin = null;
				$.ajax({ 
		        	url:"../../../admin/getSession.action",
	                type:'post',
	                async:false,
	                dataType:'json',
	                success:function(mes){
	                	if (mes!=null && mes!="") {
	                		admin = mes;
						}
	                }
	        	});
				return admin;
			}
		  	
		    //ajax加载动画
		    $(function () {
	            $.ajaxSetup({
	                layerIndex:-1,
	                beforeSend: function () {
	                    this.layerIndex = layer.load(1, { shade: [0.8, '#ffffff'] });
	                },
	                complete: function () {
	                    layer.close(this.layerIndex);
	                },
	                error: function () {
	                    layer.alert('部分数据加载失败，可能会导致页面显示异常，请刷新后重试', {
	                        skin: 'layui-layer-molv'
	                       , closeBtn: 0
	                       , shift: 4 //动画类型
	                    });
	                }
	            });
	        });
		</script>
	</body>
</html>
